<template>
  <div class="grade-management">
    <div class="header">
      <h2>成绩管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-row">
          <div class="form-group">
            <label>学年：</label>
            <el-select v-model="searchForm.academicYear" placeholder="请选择学年" clearable>
              <el-option label="2024-2025" value="2024-2025" />
              <el-option label="2023-2024" value="2023-2024" />
              <el-option label="2022-2023" value="2022-2023" />
            </el-select>
          </div>
          <div class="form-group">
            <label>学期：</label>
            <el-select v-model="searchForm.semester" placeholder="请选择学期" clearable>
              <el-option label="第一学期" value="第一学期" />
              <el-option label="第二学期" value="第二学期" />
            </el-select>
          </div>
          <div class="form-group">
            <label>课程名称：</label>
            <el-input v-model="searchForm.courseName" placeholder="请输入课程名称" clearable />
          </div>
          <div class="form-group">
            <label>学生姓名：</label>
            <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" clearable />
          </div>
        </div>
        <div class="button-group">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAddGrade">录入成绩</el-button>
          <el-button 
            type="warning" 
            :disabled="selectedGrades.length === 0"
            @click="handleBatchSubmit"
          >
            批量送审
          </el-button>
        </div>
        <div class="student-info" v-if="studentList.length > 0">
          <el-alert 
            :title="`当前共加载 ${studentList.length} 名学生，来自 ${getUniqueClasses().length} 个班级：${getUniqueClasses().join('、')}`"
            type="info" 
            :closable="false"
            style="margin-top: 15px;"
          />
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        stripe 
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="courseName" label="课程名称" width="150" />
        <el-table-column prop="academicYear" label="学年" width="100" />
        <el-table-column prop="semester" label="学期" width="100" />
        <el-table-column prop="usualScore" label="平时成绩" width="100">
          <template #default="scope">
            {{ scope.row.usualScore || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="examScore" label="考试成绩" width="100">
          <template #default="scope">
            {{ scope.row.examScore || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalScore" label="总成绩" width="100">
          <template #default="scope">
            {{ scope.row.totalScore || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="letterGrade" label="等级" width="80">
          <template #default="scope">
            <el-tag :type="getGradeTagType(scope.row.letterGrade)">
              {{ scope.row.letterGrade || '--' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 0"
              type="success" 
              size="small" 
              @click="handleEdit(scope.row)"
            >
              录入成绩
            </el-button>
            <template v-else>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleEdit(scope.row)"
                :disabled="scope.row.status > 1"
              >
                修改
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="handleSubmit(scope.row)"
                :disabled="scope.row.status > 1"
              >
                送审
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 成绩录入/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form 
        :model="gradeForm" 
        :rules="gradeRules" 
        ref="gradeFormRef"
        label-width="100px"
      >
        <div class="form-row">
          <div class="form-col">
            <el-form-item label="学生信息" prop="studentId">
              <el-select v-model="gradeForm.studentId" placeholder="请选择学生" :disabled="isEdit" filterable>
                <el-option 
                  v-for="student in studentList" 
                  :key="student.id"
                  :label="`${student.studentNo} - ${student.name} (${student.className || '未分班'})`"
                  :value="student.id"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ student.studentNo }} - {{ student.name }}</span>
                    <span style="color: #8492a6; font-size: 13px;">{{ student.className || '未分班' }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="form-col">
            <el-form-item label="课程信息" prop="courseId">
              <el-select v-model="gradeForm.courseId" placeholder="请选择课程" :disabled="isEdit">
                <el-option 
                  v-for="course in courseList" 
                  :key="course.id"
                  :label="course.courseName"
                  :value="course.id"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="form-col">
            <el-form-item label="学年" prop="academicYear">
              <el-select v-model="gradeForm.academicYear" placeholder="请选择学年" :disabled="isEdit">
                <el-option label="2024-2025" value="2024-2025" />
                <el-option label="2023-2024" value="2023-2024" />
                <el-option label="2022-2023" value="2022-2023" />
              </el-select>
            </el-form-item>
          </div>
          <div class="form-col">
            <el-form-item label="学期" prop="semester">
              <el-select v-model="gradeForm.semester" placeholder="请选择学期" :disabled="isEdit">
                <el-option label="第一学期" value="第一学期" />
                <el-option label="第二学期" value="第二学期" />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="form-col">
            <el-form-item label="平时成绩" prop="usualScore">
              <el-input-number 
                v-model="gradeForm.usualScore" 
                :min="0" 
                :max="100" 
                :precision="1"
                placeholder="请输入平时成绩"
              />
            </el-form-item>
          </div>
          <div class="form-col">
            <el-form-item label="考试成绩" prop="examScore">
              <el-input-number 
                v-model="gradeForm.examScore" 
                :min="0" 
                :max="100" 
                :precision="1"
                placeholder="请输入考试成绩"
              />
            </el-form-item>
          </div>
        </div>
        <div class="grade-preview" v-if="gradeForm.usualScore && gradeForm.examScore">
          <div class="preview-item">
            <span>总成绩：</span>
            <span class="score">{{ calculateTotalScore() }}</span>
          </div>
          <div class="preview-item">
            <span>等级：</span>
            <el-tag :type="getGradeTagType(calculateLetterGrade())">
              {{ calculateLetterGrade() }}
            </el-tag>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { gradeTeacherApi } from '@/api/grade'
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedGrades = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive({
  academicYear: '', // 先留空，让用户可以看到所有数据
  semester: '',
  courseName: '',
  studentName: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 成绩表单
const gradeForm = reactive({
  id: null,
  studentId: null,
  courseId: null,
  academicYear: '',
  semester: '',
  usualScore: null,
  examScore: null
})

// 表单校验规则
const gradeRules = {
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  academicYear: [{ required: true, message: '请选择学年', trigger: 'change' }],
  semester: [{ required: true, message: '请选择学期', trigger: 'change' }],
  usualScore: [{ required: true, message: '请输入平时成绩', trigger: 'blur' }],
  examScore: [{ required: true, message: '请输入考试成绩', trigger: 'blur' }]
}

// 学生和课程数据
const studentList = ref([])
const courseList = ref([])

// 表单引用
const gradeFormRef = ref()

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '修改成绩' : '录入成绩')

// 页面加载时获取数据
onMounted(() => {
  loadGrades()
  loadStudentList()
  loadCourseList()
})

// 加载成绩列表
const loadGrades = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    console.log('=== 发送请求参数 ===', params)
    const response = await gradeTeacherApi.getTeacherGrades(params)
    console.log('=== API完整响应 ===', response)
    console.log('=== 响应数据结构 ===', response.data)
    console.log('=== response.data的类型 ===', typeof response.data)
    console.log('=== response.data是否有code字段 ===', 'code' in response.data)
    console.log('=== response.data.code的值 ===', response.data.code)
    
    // 检查响应数据结构：可能是直接的分页数据，也可能是包装过的
    let pageData;
    if (response.data.code === 200) {
      console.log('=== 使用包装格式 ===')
      pageData = response.data.data
    } else if (response.data.records) {
      console.log('=== 使用直接格式 ===')
      pageData = response.data
    } else {
      console.log('=== 未知数据格式 ===', response.data)
      return
    }
    
    console.log('=== 最终pageData ===', pageData)
    console.log('=== records字段 ===', pageData.records)
    console.log('=== records数量 ===', pageData.records?.length)
    console.log('=== 第一条记录详情 ===', pageData.records?.[0])
    
    tableData.value = pageData.records || []
    pagination.total = pageData.total || 0
    
    console.log('=== 设置后的tableData ===', tableData.value)
    console.log('=== 设置后的tableData长度 ===', tableData.value.length)
    console.log('=== 设置后的total ===', pagination.total)
    
    // 延迟检查DOM更新
    setTimeout(() => {
      console.log('=== 1秒后的tableData ===', tableData.value)
      console.log('=== 页面表格是否有数据 ===', document.querySelectorAll('.el-table__row').length)
    }, 1000)
  } catch (error) {
    console.error('获取成绩列表失败:', error)
    ElMessage.error('获取成绩列表失败')
  } finally {
    loading.value = false
  }
}

// 加载学生列表
const loadStudentList = async () => {
  try {
    const params = {
      academicYear: searchForm.academicYear,
      semester: searchForm.semester
    }
    const response = await gradeTeacherApi.getTeacherStudents(params)
    if (response.data.code === 200) {
      studentList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  }
}

// 加载课程列表
const loadCourseList = async () => {
  try {
    const params = {
      academicYear: searchForm.academicYear,
      semester: searchForm.semester
    }
    const response = await gradeTeacherApi.getTeacherCourses(params)
    if (response.data.code === 200) {
      courseList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadGrades()
  // 重新加载学生列表和课程列表（根据学年学期筛选）
  loadStudentList()
  loadCourseList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 添加成绩
const handleAddGrade = () => {
  isEdit.value = false
  resetGradeForm()
  dialogVisible.value = true
}

// 编辑成绩
const handleEdit = (row) => {
  if (row.status === 0) {
    // 未录入成绩，当作新增处理
    isEdit.value = false
    resetGradeForm()
    // 预填充学生和课程信息
    gradeForm.studentId = row.studentId
    gradeForm.courseId = row.courseId
    gradeForm.academicYear = row.academicYear
    gradeForm.semester = row.semester
  } else {
    // 已有成绩，当作编辑处理
    isEdit.value = true
    Object.assign(gradeForm, row)
  }
  
  dialogVisible.value = true
}

// 单个送审
const handleSubmit = async (row) => {
  try {
    await ElMessageBox.confirm('确认要送审该成绩吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await gradeTeacherApi.submitGradeForReview(row.id)
    ElMessage.success('送审成功')
    loadGrades()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('送审失败')
    }
  }
}

// 批量送审
const handleBatchSubmit = async () => {
  try {
    await ElMessageBox.confirm(`确认要送审选中的 ${selectedGrades.value.length} 条成绩吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const gradeIds = selectedGrades.value.map(grade => grade.id)
    await gradeTeacherApi.batchSubmitGradeForReview(gradeIds)
    ElMessage.success('批量送审成功')
    loadGrades()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量送审失败')
    }
  }
}

// 保存成绩
const handleSave = async () => {
  try {
    await gradeFormRef.value.validate()
    
    const formData = {
      ...gradeForm,
      teacherId: userStore.currentUser.teacherId,
      teacherName: userStore.currentUser.name
    }
    
    // 根据选择的学生和课程填充信息
    const selectedStudent = studentList.value.find(s => s.id === gradeForm.studentId)
    const selectedCourse = courseList.value.find(c => c.id === gradeForm.courseId)
    
    if (selectedStudent) {
      formData.studentNo = selectedStudent.studentNo || ''
      formData.studentName = selectedStudent.name || ''
      formData.className = selectedStudent.className || ''
    }
    
    if (selectedCourse) {
      formData.courseName = selectedCourse.courseName || ''
    }
    
    // 数据验证
    if (!formData.studentId) {
      ElMessage.error('请选择学生')
      return
    }
    if (!formData.courseId) {
      ElMessage.error('请选择课程')
      return
    }
    if (!formData.academicYear) {
      ElMessage.error('请选择学年')
      return
    }
    if (!formData.semester) {
      ElMessage.error('请选择学期')
      return
    }
    
    if (isEdit.value) {
      await gradeTeacherApi.updateGrade(formData)
      ElMessage.success('修改成功')
    } else {
      await gradeTeacherApi.saveGrade(formData)
      ElMessage.success('保存成功')
    }
    
    dialogVisible.value = false
    loadGrades()
  } catch (error) {
    ElMessage.error(isEdit.value ? '修改失败' : '保存失败')
  }
}

// 关闭对话框
const handleDialogClose = () => {
  resetGradeForm()
}

// 重置表单
const resetGradeForm = () => {
  Object.keys(gradeForm).forEach(key => {
    gradeForm[key] = key === 'id' ? null : ''
  })
  gradeForm.usualScore = null
  gradeForm.examScore = null
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedGrades.value = selection.filter(item => item.status <= 1)
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadGrades()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadGrades()
}

// 计算总成绩
const calculateTotalScore = () => {
  if (gradeForm.usualScore && gradeForm.examScore) {
    return (gradeForm.usualScore * 0.3 + gradeForm.examScore * 0.7).toFixed(1)
  }
  return 0
}

// 计算等级成绩
const calculateLetterGrade = () => {
  const totalScore = parseFloat(calculateTotalScore())
  if (totalScore >= 90) return 'A'
  if (totalScore >= 80) return 'B'
  if (totalScore >= 70) return 'C'
  if (totalScore >= 60) return 'D'
  return 'F'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未录入',
    1: '已保存',
    2: '已送审',
    3: '已通过',
    4: '已退回'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: '',  // 未录入状态不显示标签
    1: 'success',
    2: 'warning',
    3: 'success',
    4: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取成绩等级标签类型
const getGradeTagType = (grade) => {
  const typeMap = {
    'A': 'success',
    'B': 'primary',
    'C': 'warning',
    'D': 'info',
    'F': 'danger'
  }
  return typeMap[grade] || 'info'
}

// 获取唯一班级列表
const getUniqueClasses = () => {
  const classes = [...new Set(studentList.value.map(student => student.className).filter(Boolean))]
  return classes.length > 0 ? classes : ['未分班']
}
</script>

<style scoped>
.grade-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-form .form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-group label {
  white-space: nowrap;
  font-weight: 500;
}

.button-group {
  display: flex;
  gap: 10px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.form-col {
  flex: 1;
}

.grade-preview {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  margin-top: 15px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.preview-item:last-child {
  margin-bottom: 0;
}

.score {
  font-weight: bold;
  color: #409eff;
  font-size: 16px;
}
</style> 